<template>
  <div class="app-content">
    <div class="content-header">
      <Row class="header-query" type="flex">
        <Col span="5">
          <Select
            v-model="params.whereMap.orgId"
            ref="treeSelect"
            placeholder="机构名称"
          >
            <Option
              v-for="item in orgList"
              :value="item.objectId"
              :key="item.objectId"
              style="display: none;"
              >{{ item.title }}</Option
            >
            <Tree
              :data="orgTreeData"
              ref="tree"
              style="padding:0 10px"
              @on-select-change="checkEng"
            ></Tree>
          </Select>
        </Col>
        <Col span="5" offset="1">
          <Select
            v-model="params.whereMap.projectId"
            placeholder="项目名称"
            clearable
          >
            <Option v-for="item in projects" :value="item.id" :key="item.id">{{
              item.shortName
            }}</Option>
          </Select>
        </Col>
        <Col span="5" offset="1">
          <DatePicker
            :value="params.whereMap.dynamicTime"
            type="month"
            placeholder="选择日期"
            @on-change="dateChange"
          ></DatePicker>
        </Col>
      </Row>
      <Row class="header-query" type="flex">
        <Col span="5">
          <Input
            placeholder="工点名称"
            v-model="params.whereMap.constructionPointName"
            clearable
          />
        </Col>
        <Col span="5" offset="1">
          <Select
            v-model="params.whereMap.distRiskGrade"
            placeholder="工点风险等级"
            clearable
          >
            <Option
              v-for="item in workLevels"
              :value="item.value"
              :key="item.value"
              >{{ item.text }}</Option
            >
          </Select>
        </Col>
        <Col span="5" offset="1">
          <Select
            v-model="params.whereMap.isWork"
            placeholder="是否在施"
            clearable
            ref="isWorkSelect"
          >
            <Option
              v-for="item in isWorkFlags"
              :value="item.value"
              :key="item.value"
              >{{ item.text }}</Option
            >
          </Select>
        </Col>
      </Row>
      <Row class="header-query" type="flex">
        <Col span="5">
          <Select
            v-model="params.whereMap.riskCategoryId"
            placeholder="作业风险类别"
            clearable
          >
            <Option
              v-for="item in riskCategories"
              :value="item.id"
              :key="item.id"
              >{{ item.riskCategoryName }}</Option
            >
          </Select>
        </Col>
        <Col span="5" offset="1">
          <Select
            v-model="params.whereMap.controlStatus"
            placeholder="管控状态"
            clearable
          >
            <Option
              v-for="item in controlStatus"
              :value="item.value"
              :key="item.value"
              >{{ item.text }}</Option
            >
          </Select>
        </Col>
        <Col span="5" offset="1">
          <Input placeholder="措施名称" v-model="params.whereMap.measures" />
        </Col>
        <Col offset="3" span="4" style="text-align: right;">
          <Button type="primary" @click="query" v-if="queryFlag">查询</Button>
        </Col>
      </Row>
    </div>
    <div class="count-box" v-if="userTypes.length > 0">
      <Row class="count-title">
        <Col span="24">
          <Icon type="md-person" class="title-icon" />
          <span class="static-title">您是</span>
          <Select
            v-model="params.whereMap.userType"
            class="count-select"
            @on-change="query"
          >
            <Option
              v-for="user in userTypes"
              :value="user.userType"
              :key="user.userType"
              >{{ user.userTypeName }}</Option
            >
          </Select>
        </Col>
      </Row>
      <Row class="count-item" type="flex" justify="space-between">
        <Col span="6"> 需您管控风险总数：{{ countModel.riskTotal }}项 </Col>
        <Col span="6"> 当前可管控：{{ countModel.currentRiskCount }}项 </Col>
        <Col span="6"> 已管控：{{ countModel.finishRiskTotal }}项 </Col>
        <Col span="6"> 管控率：{{ countModel.riskPercent }} </Col>
      </Row>
      <Row class="count-item" type="flex" justify="space-between">
        <Col span="6"> 需您管控措施总数：{{ countModel.measuresTotal }}项 </Col>
        <Col span="6">
          当前可管控：{{ countModel.currentMeasuresCount }}项
        </Col>
        <Col span="6"> 已管控：{{ countModel.finishMeasuresTotal }}项 </Col>
        <Col span="6"> 管控率：{{ countModel.measuresPercent }} </Col>
      </Row>
    </div>
    <div class="content-body" v-if="userTypes.length > 0">
      <Row>
        <Col class="app-tabs">
          <Tabs value="1" @on-click="tabChange">
            <TabPane label="I级" name="1"> </TabPane>
            <TabPane label="II级" name="2"></TabPane>
            <TabPane label="III级" name="3"></TabPane>
            <TabPane label="IV级" name="4"></TabPane>
          </Tabs>
        </Col>
      </Row>
      <Table
        class="table"
        ref="listTable"
        border
        :columns="columns"
        :data="list"
        no-data-text="暂无数据"
        @on-selection-change="selectChangeRiado"
      >
        <template slot-scope="{ row }" slot="operation">
          <a @click="toControl(row.id)" v-if="controlFlag && 1 === row.type"
            >管控</a
          >
          <a @click="initDetail(row.id)" v-if="detailFlag">详情</a>
        </template>
        <template slot-scope="{ row }" slot="status">
          <span v-if="1 == row.status" class="status--yellow">{{
            row.statusName
          }}</span>
          <span v-else-if="2 == row.status" class="status--red">{{
            row.statusName
          }}</span>
          <span v-else class="status--green">{{ row.statusName }}</span>
        </template>
      </Table>
      <Row type="flex" justify="center">
        <Col>
          <Page
            class="pagination"
            :total="params.totalRecord"
            :current="params.currentPage"
            :page-size="params.pageSize"
            :pageSizeOpts="pageSizeOpts"
            @on-change="pageChange"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-total
            show-sizer
          />
        </Col>
      </Row>
    </div>
    <div class="no-data" v-if="0 === userTypes.length">
      <div>
        <img src="../../../assets/images/process-no-data.png" />
        <p>暂无可管控数据</p>
      </div>
    </div>
    <Modal v-model="isInquiries" title="业务问询" width="50%" ok-text="提交" :footer-hide="true">
      <div class="modal-content">
        <inquiries ref="isInquiriesBox" :checkedRows="checkedRows" :businessType="businessType" @modelBox="modelBox" @person="person"></inquiries>
      </div>
    </Modal>
    <Modal v-model="personModel" title="选择人" width="80%" ok-text="提交" :footer-hide="true">
      <div class="modal-content">
        <checkPerson @personBox="personBox"></checkPerson>
      </div>
    </Modal>
    <span class="inquiries" @click="replyChild()">问询</span>
  </div>
</template>

<script>
import inquiries from '../../../components/modules/inquiries/index'
import checkPerson from '../../../components/modules/inquiries/checkPerson'
export default {
  components:{
      inquiries,
      checkPerson
    },
  name: 'procedure-control',
  data() {
    return {
      businessType:'businesstype_control',
      isInquiries:false,
      personModel:false,
      pageSizeOpts: [10, 20, 50, 100],
      userTypes: [],
      riskCategories: [],
      params: {
        currentPage: 1,
        pageSize: 10,
        totalRecord: 0,
        whereMap: {
          orgId: '',
          projectId: '',
          dynamicTime: this.initDate(),
          riskLevel: 1,
          constructionPointName: '',
          isWork: 0,
          distRiskGrade: 0,
          riskCategoryId: '',
          controlStatus: 0,
          measures: '',
          userType: 0
        }
      },
      workLevels: [
        { text: 'I级', value: 1 },
        { text: 'II级', value: 2 },
        { text: 'III级', value: 3 },
        { text: 'IV级', value: 4 }
      ],
      isWorkFlags: [{ text: '是', value: 1 }, { text: '否', value: 2 }],
      controlStatus: [
        { text: '未管控', value: 1 },
        { text: '管控到位', value: 3 },
        { text: '管控不到位', value: 2 }
      ],
      orgTreeData: [],
      orgList: [],
      projects: [],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          width: 70,
          align: 'center',
          title: '序号',
          render: (h, params) => {
            return h(
              'span',
              this.params.pageSize * (this.params.currentPage - 1) +
                params.index +
                1
            )
          }
        },
        {
          title: '公司名称',
          key: 'enterpriseName',
          align: 'center'
        },
        {
          title: '项目名称  ',
          key: 'projectName',
          align: 'center'
        },
        {
          title: '工点名称',
          key: 'constructionPointName',
          align: 'center'
        },
        {
          title: '作业风险名称',
          key: 'riskName',
          align: 'center'
        },
        {
          title: '作业风险类型',
          key: 'riskCategoryNames',
          align: 'center'
        },
        {
          title: '管控措施',
          key: 'measures',
          align: 'center'
        },
        {
          title: '管控状态',
          key: 'statusName',
          align: 'center',
          slot: 'status'
        },
        {
          title: '操作',
          slot: 'operation',
          align: 'center',
          className: 'table--operation'
        }
      ],
      list: [],
      countModel: {},
      checkedRows: [],
      // 权限
      queryFlag: false,
      controlFlag: false,
      detailFlag: false
    }
  },
  methods: {
    // 复选框
    selectChangeRiado(e) {
      this.checkedRows = e
    },
    // 唤醒问询框
    replyChild(){
        if(this.checkedRows.length > 5){
          this.$Message.warning('最多可选5条措施进行批量问询')
          return 
        }else if(this.checkedRows.length == 0){
            this.$Message.warning('请先选择需要问询的措施')
            return
        }else{
            let isM = true,self = this
            try{
                self.checkedRows.forEach((e,index)=>{
                    if(index>0){
                        if(e.projectId != self.checkedRows[index-1].projectId){
                            this.$Message.warning('仅能选择同一项目下的措施询问')
                            isM = false
                            throw Error()
                        }
                    }
                })
            }catch(e){}
            if(isM){
                this.isInquiries = true
                this.$refs.isInquiriesBox.isModel()
            }
        }
      },
      // 关闭问询框
      modelBox(){
        this.isInquiries = false
      },
      // 打开人员选择框
      person(){
        this.personModel = true
      },
      // 关闭人员选择框
      personBox(){
        this.personModel = false
      },
    getOrgTree() {
      if (this.params.whereMap.orgId) {
        this.query()
      } else {
        this.$api.measurePlan.getOrgTree().then(({ code, data, message }) => {
          if (code === 200) {
            this.orgTreeData = data
            this.$nextTick(() => {
              const tree = this.$refs.tree
              tree.handleSelect(tree.data[0].nodeKey)
              // 身份切换查询
              this.$api.processControl
                .userTypes()
                .then(({ code, data, message }) => {
                  if (200 === code) {
                    this.userTypes = data
                    this.userTypes = Object.freeze(this.userTypes)
                    // this.userTypes = []
                    this.params.whereMap.userType =
                      this.userTypes.length > 0 ? this.userTypes[0].userType : 0
                    this.query()
                  } else {
                    this.$Message.error(message)
                  }
                })
            })
          } else {
            this.$Message.error(message)
          }
        })
      }
    },
    // 获取风险类型
    initRiskCategories() {
      this.$api.measuresLibrary
        .getRiskCategoryFindAll()
        .then(({ code, data }) => {
          if (code === 200) {
            this.riskCategories = data
          }
        })
    },
    checkEng(selected, current) {
      const { objectId, title } = current
      this.params.whereMap.orgId = objectId
      this.params.whereMap.projectId = ''
      this.orgList.push({ objectId, title })
      this.$refs.treeSelect.visible = false
      this.queryProjects(objectId)
    },
    queryProjects(id) {
      this.projects = []
      this.$api.measurePlan.getProList(id).then(({ code, data, message }) => {
        if (code === 200) {
          this.projects = data
        } else {
          this.$Message.error(message)
        }
      })
    },
    query() {
      this.queryCount()
      this.queryList()
    },
    queryList(page = 1, size = 10) {
      this.params.currentPage = page
      this.params.pageSize = size
      this.$api.processControl
        .queryPage(this.params)
        .then(({ code, data, message }) => {
          if (200 === code) {
            this.list = data.resultObject
            this.params.totalRecord = data.totalRecord
          } else {
            this.$Message.error(message)
          }
        })
    },
    queryCount() {
      this.$api.processControl
        .statistics(this.params.whereMap)
        .then(({ code, data, message }) => {
          if (200 === code) {
            this.countModel = data
          } else {
            this.$Message.error(message)
          }
        })
    },
    pageChange(page) {
      this.params.currentPage = page
      this.queryList(page, this.params.pageSize)
    },
    pageSizeChange(size) {
      this.params.pageSize = size
      this.queryList(this.params.currentPage, size)
    },
    initDetail(id) {
      this.$router.push({
        name: 'procedure-control-detail',
        params: {
          id
        }
      })
    },
    toControl(id) {
      this.$router.push({
        name: 'procedure-control-edit',
        params: {
          id
        }
      })
    },
    tabChange(index) {
      this.params.whereMap.riskLevel = index
      this.queryList()
    },
    initDate() {
      const date = new Date()
      const year = date.getFullYear()
      let month = date.getMonth() + 1
      month = month > 9 ? month : `0${month}`
      return `${year}-${month}`
    },
    dateChange(e) {
      this.params.whereMap.dynamicTime = e
    },
    init() {
      // 按钮权限
      const buttons = JSON.parse(localStorage.getItem('buttonList'))
      if (buttons) {
        const routeName = this.$route.name
        const routeButtons = buttons.find(
          b => routeName === Object.keys(b).join('')
        )
        const codes = routeButtons[routeName].map(b => b.code)
        this.queryFlag = codes.includes('P_1002_01')
        this.controlFlag = codes.includes('P_1002_02')
        this.detailFlag = codes.includes('P_1002_03')
      }
    }
  },
  mounted() {
    this.init()
    this.initRiskCategories()
  },
  activated() {
    this.getOrgTree()
  }
}
</script>

<style lang="scss" scoped>
.app-content {
  .table {
    .status--green {
      color: #3bbb0a;
    }
    .status--yellow {
      color: #e7af63;
    }
    .status--red {
      color: #ef3e43;
    }
  }
  .header-query {
    margin-bottom: 15px !important;
  }
  .count-box {
    margin-bottom: 15px;
    padding: 20px 30px;
    background-color: #f5f8fc;
    .count-title {
      margin-bottom: 10px;
      color: #0099ff;
      font-weight: 600;
      .title-icon {
        margin-right: 5px;
      }
      .static-title {
        vertical-align: middle;
      }
      .count-select {
        width: 180px;
        color: #0099ff;
        & /deep/ .ivu-select-selection {
          margin-top: 1px;
          border: none;
          background: transparent;
          .ivu-select-selected-value {
            padding: 0;
          }
          .ivu-select-arrow {
            top: calc(50% - 1px);
            color: #0099ff;
          }
        }
      }
    }
    .count-item {
      color: #627181;
      &:not(:last-child) {
        margin-bottom: 10px;
      }
    }
  }
  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100% - 150px);
    background-color: #f5f8fc;
    p {
      margin-top: 10px;
      color: #999999;
    }
  }
}
</style>
